# -*- coding:utf8 -*-
import json
import traceback
import os
import re
import typing
from scrapy import Request
from squirrel_core.commons.utils.tools import calc_str_md5, upload_file
from squirrel_core.frame.spider_makaka import MakakaSpider

file_path = os.environ.get("FILE_PATH", "/")


class svstiming_score(MakakaSpider):
    name = "svstiming_score"
    serialNumber = ""
    header = {
        "Host": "public.svstiming.cn",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
        "Accept": "application/json, text/javascript, */*; q=0.01"
    }
    specific_settings = {
        "HTTPERROR_ALLOWED_CODES": [400]
    }

    def get_ext_requests_or_urls(self, data=None):
        if data and isinstance(data, str):
            data = json.loads(data)
        if data and isinstance(data, typing.MutableMapping):
            self.serialNumber = data.get("serialNumber", "")
            race_id = data.get("spider_config", {}).get("race_id", "")
            user_id = data.get("spider_config", {}).get("user_id", "")
            race_no = data.get("spider_config", {}).get("race_no", "")
            user_name = data.get("spider_config", {}).get("user_name", "")
            card_num = data.get("spider_config", {}).get("card_num", "")
            race_name = data.get("spider_config", {}).get("race_name", "").replace(" ", "")
            home_url = data.get("spider_config", {}).get("url", "")
            if not all([race_no, card_num, home_url]):
                self.logger.info("参数不全")
                self.upload_procedure({"serialNumber": self.serialNumber, "code": 203, "message": "参数不全"})
                self.close_after_idle = True
                self.force_to_close_spider = True
            else:
                self.upload_procedure({"serialNumber": self.serialNumber, "code": 100, "message": "任务启动成功"})
                game_id = "".join(re.findall(r"gameid=(\d+)", home_url)).strip()
                keyword = f"{race_no}{card_num[-4:]}"
                url = f"https://public.svstiming.cn/openapi/openquery?type=resultnumber&gameid={game_id}&bib={keyword}"
                yield Request(url=url, callback=self.parse, dont_filter=True, errback=self.err_parse, headers=self.header,
                              meta={"race_id": race_id, "user_id": user_id, "user_name": user_name, "card_num": card_num,
                                    "race_name": race_name, "game_id": game_id, "race_no": race_no})

    def parse(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_name = response.meta.get("race_name", "")
        game_id = response.meta.get("game_id", "")
        race_no = response.meta.get("race_no", "")
        card_num = response.meta.get("card_num", "")
        user_name = response.meta.get("user_name", "")
        try:
            self.logger.info(f"开始获取{user_name}的成绩")
            data_list = json.loads(response.text).get("resultnumber", [])
            if data_list:
                for data in data_list:
                    event_name = data.get("eventname", "")
                    section_list = data.get("results", "")
                    score_info = []
                    for data in section_list:
                        cp_name = data.get("name", "")
                        stop_time = data.get("netresult", "")
                        speed = data.get("pace", "")
                        distance = data.get("dis", "")
                        score_info.append(
                            {"cp_name": cp_name, "start_time": "", "score": stop_time, "distance": distance,
                             "pace": speed})
                    if score_info:
                        score_info[-1]["cp_name"] = "FINISH"
                    score_data = {"race_name": race_name, "itemName": event_name, "name": data.get("name", ""),
                                  "raceNo": data.get("bib", ""), "pace": "", "distance": "",
                                  "shotScore": data.get("gunresult", ""), "score": data.get("netresult", ""),
                                  "fastPace": "", "slowPace": "", "certImg": "", "sectionScore": score_info}
                    url = f"https://public.svstiming.cn/openapi/openquery?type=cert&gameid={game_id}&eventname={event_name}&bib={race_no}&idnumber={card_num}"
                    yield Request(url=url, callback=self.parse_cert, errback=self.err_parse, dont_filter=True, headers=self.header,
                                  meta={"race_id": race_id, "user_id": user_id, "score_data": score_data,
                                        "user_name": user_name, "race_no": race_no})
            else:
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str({"msg": "未查到成绩信息"})}
                yield result
        except Exception:
            self.logger.info(f"获取{user_name}的成绩时出错{response.url}：{traceback.format_exc()}")

    def parse_cert(self, response):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        score_data = response.meta.get("score_data", {})
        user_name = response.meta.get("user_name", "")
        race_no = response.meta.get("race_no", "")
        try:
            self.logger.info(f"开始解析证书链接:{response.url}")
            cert_link = json.loads(response.text).get("cert", {}).get("path", "")
            if cert_link:
                cert_url = response.urljoin(cert_link)
                yield Request(url=cert_url, callback=self.parse_pic, errback=self.err_parse, dont_filter=True,
                              meta={"race_id": race_id, "user_id": user_id, "score_data": score_data,
                                    "user_name": user_name, "race_no": race_no})
            else:
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str(score_data)}
                yield result
        except Exception:
            self.logger.info(f"解析证书链接时出错{response.url}：{traceback.format_exc()}")

    def parse_pic(self, response):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        score_data = response.meta.get("score_data", {})
        user_name = response.meta.get("user_name", "")
        race_no = response.meta.get("race_no", "")
        try:
            self.logger.info(f"开始下载{user_name}的证书：{response.url}")
            pic_md5 = calc_str_md5(response.url)
            pic_name = f"{race_no}_{pic_md5}.jpg"
            dir_path = os.path.join(file_path, "picture", self.name_first)
            if not os.path.exists(dir_path):
                os.makedirs(dir_path)
            save_path = os.path.join(dir_path, pic_name)
            if not os.path.exists(save_path):
                with open(save_path, "wb") as f:
                    f.write(response.body)
                upload_path = f"flow/{race_id}/{user_id}/pic/{pic_name}"
                upload_flag = upload_file(save_path, upload_path)
                if upload_flag:
                    self.logger.info(f"{save_path}上传成功：{upload_path}")
                else:
                    self.logger.info(f"{save_path}上传失败：{upload_path}")
                score_data["certImg"] = upload_path
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str(score_data)}
                yield result
        except Exception:
            self.logger.info(f"下载{user_name}证书时出错{response.url}：{traceback.format_exc()}")

    def err_parse(self, failure):
        self.logger.warning(f"请求失败：{failure.request.url},错误原因:{traceback.format_exc()}")
